import React from "react";
import { Navigate, useLocation } from "react-router-dom";
import { useSelector } from "react-redux";

// 权限保护
const PrivateRoute = ({ component: Component, ...rest }) => {
  let location = useLocation(); // 类似 window.location 对象
  const token = useSelector((state) => state.user.token);

  return token ? (
    <Component {...rest} />
  ) : (
    <Navigate
      to={{
        pathname: "/login",
        state: { from: location }, // 重定向登录页，并且记录想要访问的页面
      }}
    />
  );
};

export default PrivateRoute;
